<template>
  <div>
    <h1>实时数据接收</h1>
    <ul>
      <li v-for="(item, index) in receivedArray" :key="index">{{ item }}</li>
    </ul>
  </div>
</template>
<script setup>
import { ref, onMounted, onUnmounted } from "vue";

const receivedArray = ref([]);
const websocket = ref();

// WebSocket连接函数
const connectWebSocket = () => {
  // 替换为您的实际WebSocket地址
  websocket.value = new WebSocket("ws://localhost:8800/data-stream");

  websocket.value.onopen = () => {
    console.log("WebSocket连接已建立");
  };

  websocket.value.onmessage = (event) => {
    try {
      // 解析接收到的JSON数据
      console.log(event,"event");
      
      const data = JSON.parse(event.data);
      console.log(data,"data");
      
      receivedArray.value = data;
    } catch (error) {
      console.error("解析WebSocket消息出错:", error);
    }
  };

  websocket.value.onclose = () => {
    console.log("WebSocket连接已关闭");
    // 可以在这里实现重连逻辑
  };

  websocket.value.onerror = (error) => {
    console.error("WebSocket错误:", error);
  };
};

// 组件挂载时初始化WebSocket连接
onMounted(() => {
  connectWebSocket();
});

// 组件卸载时关闭WebSocket连接
onUnmounted(() => {
  if (websocket && websocket.readyState === WebSocket.OPEN) {
    websocket.close();
  }
});
</script>